<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!--警示框 -->
      <el-alert
        title="添加商品消息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步奏条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左边分类 el-tabs 外面需要嵌套一个form标签 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <!-- 基本消息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格" prop="goods_price" type="">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="CateList"
                :props="cateProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="imgUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 点击图片显示对话框 -->
    <el-dialog title="预览窗口" :visible.sync="handleDialogVisible" width="50%">
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import  _  from 'lodash'

export default {
  data() {
    return {
      activeIndex: '0',
      // 添加商品的表单对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 商品所属的分类数组
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs:[]
      },
      // 验证规则
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur',
          },
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur',
          },
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur',
          },
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur',
          },
        ],
        goods_cat: [
          {
            required: true,
            message: '请输入商品分类',
            trigger: 'blur',
          },
        ],
      },
      // 存储级联数据
      CateList: [],
      // 级联的内部配置
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 获取动态参数
      manyTableData: [],
      // 获取静态参数
      onlyTableData: [],
      // 设置图片上传地址
      imgUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 给图片添加一个token头 因为upload有自己的上传方法 没有使用我们自己的
      headersObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      handleDialogVisible: false,
      previewPath: '',
    }
  },

  created() {
    this.getCateList()
  },
  methods: {
    // 获取分类数据列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.$message.success('获取成功')
      console.log(res)
      this.CateList = res.data
    },
    //
    handleChange() {
      console.log(this.addForm.goods_cat)
      // 判断是否选了第三级别 不是就清空

      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // beforeTabLeave 当点击切换左边分类 则会发起这个请求
    // activeName即将进入的页面 oldActiveName准备从这个页面进入activeName
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择分类')
        return false
      }
    },
    // 处理不同页面的效果
    async tabClicked() {
      if (this.activeIndex === '1') {
        console.log('cateid:' + this.cateId)
        // 此时已进入商品参数页面
        // 发起get请求
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取失败')
        }
        this.$message.success('获取成功')
        // 以逗号分隔
        res.data.forEach((item) => {
          // 判断长度是否等于零 等于零就返回空数组 不是就以逗号分隔
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        })
        this.manyTableData = res.data
        console.log('res.data____________-' + this.manyTableData)
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态失败')
        }
        this.$message.success('获取静态成功')
        // 赋值给一个数组
        this.onlyTableData = res.data

        console.log('res.data____________' + res.data)
      }
    },
    // 处理图片显示的效果
    handlePreview(file) {
      console.log(file)
      this.previewPath = file.response.data.url
      console.log('file.response.data.url=' + file.response.data.url)
      this.handleDialogVisible = true
    },
    // 图片×号 删除图片
    handleRemove(file) {
      console.log(file)
      // 获取点击X号的那个图片值
      const filePath = file.response.data.tmp_path
      // 查询与filePath相同的值
      const i = this.addForm.pics.findIndex((x) => {
        x.pics === filePath
      })
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    // 监听图片上传成功信息
    handleSuccess(response) {
      console.log(response)
      const resInfo = { pics: response.data.tmp_path }
      this.addForm.pics.push(resInfo)
      console.log(this.addForm)
    },
    // 添加商品的按钮
    async add() {
      console.log(this.addForm)
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return this.$message.error('请填必选项目')
      })
      // 到这里代表校验成功
              // 但是添加业务逻辑 因为const是浅拷贝 我们需要深拷贝
      // 所以调用_.cloneDeep
      const fo =  _.cloneDeep(this.addForm)
      // 把goods_cat 的分隔后重新复制
      fo.goods_cat = fo.goods_cat.join(',')


      // 还需要把静态参数和动态参数 添加到attrs数组中
      // console.log("动态="+this.manyTableData)
      // 动态属性
        this.manyTableData.forEach(item=>{
          const newInfo = {
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
      // console.log("静态="+this.onlyTableData)
      // 静态属性
        this.onlyTableData.forEach(item=>{
          const newInfo = {
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })

        fo.attrs = this.addForm.attrs
        console.log(fo)
      // 发起post请求
      const { data: res } = await this.$http.post('goods',fo)
      if (res.meta.status !== 201) {
        return this.$message.error('添加失败')
      }
      this.$message.success('添加成功')
      this.$router.push('/goods')
    },


  },
  computed: {
    // 获取长度为3的id
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  margin: 0 auto;
}
</style>
